package com.bootdo.elasticsearch.config;

import com.bootdo.common.utils.StringUtils;
import com.bootdo.elasticsearch.util.EsSearch;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.Objects;

/**
 * @Author wukq
 * @Date: 2020/4/26 11:42
 * @Description: elasticsearch配置类，和智慧工匠的不一样，这个是集群的配置
 * @Slf4j 注解是lombok的日志注解，可以自行删除
 */
@Slf4j
@Configuration
public class ElasticsearchConfig {
    private static final int ADDRESS_LENGTH = 2;

    @Value("${esConfig.ip}")
    private String[] ipAddress;


    @Value("${esConfig.schemeName}")
    private String schemeName;

    @Value("${esConfig.socketTimeOut}")
    private Integer socketTimeOut;

    @Value("${esConfig.connectionTimeOut}")
    private Integer connectionTimeOut;

    @Value("${esConfig.connectionRequestTimeOut}")
    private Integer connectionRequestTimeOut;

    /**
     * Objects::nonNull 这个是啥符号
     * 此种写法是Java8 Lambda表达式
     * 双冒号运算就是Java中的方法引用 method references
     * 1.表达式：
     * person -> person.getName();
     * 可以替换成：
     * Person::getName
     */
    @Bean
    public RestClientBuilder restClientBuilder() {
        HttpHost[] hosts = Arrays.stream(ipAddress)
                .map(this::makeHttpHost)
                .filter(Objects::nonNull)
                .toArray(HttpHost[]::new);
        log.debug("hosts:{}", Arrays.toString(hosts));
        return RestClient.builder(hosts);
    }

    @Bean(name = "highLevelClient")
    public RestHighLevelClient highLevelClient(@Autowired RestClientBuilder restClientBuilder) {
        restClientBuilder.setMaxRetryTimeoutMillis(connectionTimeOut);
        return new RestHighLevelClient(restClientBuilder);
    }

    private HttpHost makeHttpHost(String s) {
        assert StringUtils.isNotEmpty(s);
        String[] address = s.split(":");
        if (address.length == ADDRESS_LENGTH) {
            String ip = address[0];
            int port = Integer.parseInt(address[1]);
            return new HttpHost(ip, port, schemeName);
        } else {
            return null;
        }
    }


    /**
     * 实例化EsSearch
     */
    @Bean
    public EsSearch esSearch() {
        EsSearch esSearch = new EsSearch();
        return esSearch;
    }
}
